/**
 * 使用方式：
 * const logger = createLogger('test')
 * logger.info('这是 info 消息')
 * logger.error('这是 error 消息')
 * logger.warn('这是 warn 消息')
 * logger.log('这是 logger 消息')
 * logger.debug('这是 debug 消息')
 */

import moment from 'moment'

export type LogType = 'debug' | 'info' | 'error' | 'warn' | 'log'

export enum LogColors {
  error = '#F56C6C',
  warn = '#E6A23C',
  debug = '#606266',
  info = '#53a8ff',
  log = '#606266',
  text = '#909399'
}

const DEBUG: string | undefined = process.env.VUE_APP_DEBUG

class Logger {
  private static instance: Logger
  constructor(readonly prefixName: string) { }

  static getInstance (prefixName: string): Logger {
    if (!this.instance) {
      this.instance = new Logger(prefixName)
    }

    return this.instance
  }

  private printConsole (logType: LogType, ...params: any): void {
    if (DEBUG !== 'false') {
      // 判断记录的是全部的还是指定级别的
      if (DEBUG === 'true' || (DEBUG && DEBUG.split(',').includes(logType))) {
        const nowTime = moment(new Date()).format('YYYY/MM/DD HH:mm:ss')
        console.log(`%c[${ nowTime }][${ this.prefixName }][${ logType }]`, `color: ${ LogColors[logType] };`, ...params)
      }
    }
  }

  public warn (...params: any): void {
    this.printConsole('warn', ...params)
  }

  public info (...params: any): void {
    this.printConsole('info', ...params)
  }

  public error (...params: any): void {
    this.printConsole('error', ...params)
  }

  public debug (...params: any): void {
    this.printConsole('debug', ...params)
  }

  public log (...params: any): void {
    this.printConsole('log', ...params)
  }
}

export function createLogger (prefixName: string): Logger {
  return new Logger(prefixName)
}